package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApChannel;
import com.heima.model.user.pojos.ApUserChannel;
import com.heima.user.mapper.ApChannelMapper;
import com.heima.user.mapper.ApUserChannelMapper;
import com.heima.user.service.ApUserChannelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class ApUserChannelServiceImpl extends ServiceImpl<ApUserChannelMapper, ApUserChannel> implements ApUserChannelService {
    
    @Resource
    private ApUserChannelMapper apUserChannelMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ApChannelMapper  apChannelMapper;
    
    @Override
    public ApUserChannel getByUserIdAndChannelId(Integer userId, Integer channelId) {
        return apUserChannelMapper.selectByUserIdAndChannelId(userId, channelId);
    }
    
    @Override
    public List<ApUserChannel> getByUserId(Integer userId) {
        return apUserChannelMapper.selectByUserId(userId);
    }
    
    @Override
    public void initUserChannels(Integer userId) {
        // 初始化用户频道订阅关系的逻辑
        // 这里可以根据业务需求实现默认频道的订阅
    }
    
    @Override
    public void syncWmChannelToUser(Integer wmChannelId, String wmChannelName, Boolean isDefault, Boolean status) {
        // 同步自媒体频道到用户端的逻辑将在ApChannelServiceImpl中实现
    }
    /**
     * 查询用户是否订阅了该频道
     * @param userId
     * @param channelId
     * @return
     */

    @Override
    public ResponseResult isSub(Integer userId, Integer channelId) {

        if(userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if(channelId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApChannel apChannel =apChannelMapper.selectOne(Wrappers.<ApChannel>lambdaQuery().eq(ApChannel::getId, channelId));
        if(apChannel == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUserChannel apUserChannel = apUserChannelMapper.selectOne(Wrappers.<ApUserChannel>lambdaQuery()
                .eq(ApUserChannel::getUserId, userId)
                .eq(ApUserChannel::getChannelId, channelId));

        Map<String, Boolean> result = new HashMap<>();
        result.put("isSub", apUserChannel != null);
        return ResponseResult.okResult(result);
    }
    /**
     * 频道订阅
     * @param userId
     * @param channelId
     * @param isSub
     * @return
     */

    @Override
    public ResponseResult sub(Integer userId, Integer channelId, Boolean isSub) {
        String key="sub"+userId;

        if(userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if(channelId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(isSub){
            ApUserChannel apUserChannel = apUserChannelMapper.selectOne(Wrappers.<ApUserChannel>lambdaQuery()
                    .eq(ApUserChannel::getUserId, userId)
                    .eq(ApUserChannel::getChannelId, channelId));
            if(apUserChannel == null){
                apUserChannel = new ApUserChannel();
                apUserChannel.setUserId(userId);
                apUserChannel.setChannelId(channelId);
                apUserChannel.setIsSubscribe(true);
                apUserChannel.setCreatedTime(new Date());
                int insert = apUserChannelMapper.insert(apUserChannel);
                if(insert>0){
                    stringRedisTemplate.opsForSet().add(key,channelId.toString());
                }
            }else{
                apUserChannel.setIsSubscribe(true);
                int i = apUserChannelMapper.updateById(apUserChannel);
                if(i>0){
                    stringRedisTemplate.opsForSet().add(key,channelId.toString());
                }
            }


        }
        else{
            ApUserChannel apUserChannel = apUserChannelMapper.selectOne(Wrappers.<ApUserChannel>lambdaQuery()
                    .eq(ApUserChannel::getUserId, userId)
                    .eq(ApUserChannel::getChannelId, channelId));
            if(apUserChannel != null){
                apUserChannel.setIsSubscribe( false);
                int i = apUserChannelMapper.updateById(apUserChannel);
                if(i>0){
                    stringRedisTemplate.opsForSet().remove(key,channelId.toString());
                }
            }



        }
        return ResponseResult.okResult(null);
    }
    @Override
    public ResponseResult getUserSubChannels(Integer userId) {
        if (userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 查询用户所有订阅的频道
        List<ApUserChannel> userChannels = apUserChannelMapper.selectList(
                Wrappers.<ApUserChannel>lambdaQuery()
                        .eq(ApUserChannel::getUserId, userId)
                        .eq(ApUserChannel::getIsSubscribe, true)
        );
        List<Integer> channelIds = userChannels.stream()
                .map(ApUserChannel::getChannelId)
                .collect(Collectors.toList());
        List<ApChannel> channels = apChannelMapper.selectBatchIds(channelIds);

        return ResponseResult.okResult(channels);
    }

}
